using UnityEngine;
using System.Collections;

public class ManagerSurvivalMode : MonoBehaviour
{
	public static int enemiesElimined = 0, rooms = 0;
	public ManagerStageBlock[] blocksToLoop;
	public ManagerStageBlock currentBlockStage;
	public ManagerStageBlock oldBlockStage;
	public bool canCheckFinal, doorOpen;
	
	public enum SurvivalState
	{
		NORMAL, SHOW_DOOR, NEXT,
	}
	public SurvivalState survivalState = SurvivalState.NORMAL;
	
	public PlayerCharacterBehaviour player;
	
	public Follower follower;
	
	public int indexBlock = 0;
	
	void Start()
	{
		enemiesElimined = 0;
		rooms = 0;
	}
	
	void Update()
	{
		if(player)
		{
			switch(survivalState)
			{
				case SurvivalState.NORMAL:
				
				follower.NewTarget(player.transform, Vector3.zero);
				
				if(doorOpen)
				{
					if(!currentBlockStage.detectorPlayerWantNext.IsFree)
					{
						ManagerGame.enableAction = false;
						survivalState = SurvivalState.NEXT;
						canCheckFinal = true;
						doorOpen = false;
					}
				}
				
				break;
				
				case SurvivalState.SHOW_DOOR:
				
				follower.NewTarget(currentBlockStage.doorExitAnimation.transform, Vector3.zero);
				
				if(follower.FinishTween)
				{
					currentBlockStage.doorExitAnimation.Play("open");
					
					if(currentBlockStage.doorExitAnimation.CanChangeAnimation)
					{
						ManagerGame.enableAction = true;
						Destroy(currentBlockStage.exitCollider.gameObject);
						survivalState = SurvivalState.NORMAL;
					}
				}
				
				break;
				
				case SurvivalState.NEXT:
				
				if(canCheckFinal)
				{
					oldBlockStage = currentBlockStage;
					
					currentBlockStage = ((GameObject)Instantiate(blocksToLoop[indexBlock].gameObject, oldBlockStage.positionToCreateNext.position, Quaternion.identity)).GetComponent<ManagerStageBlock>();
					
					currentBlockStage.enterCollider.enabled = false;
					
					follower.NewMaxMin(currentBlockStage.minCamera, currentBlockStage.maxCamera);
					
					rooms++;
					
					canCheckFinal = false;
					
					indexBlock ++;
					if(indexBlock == blocksToLoop.Length)
					{
						indexBlock = 0;
					}
				}
				else
				{
					if(player.TryMoveTo(currentBlockStage.positionToStartStage.position))
					{
						currentBlockStage.enterCollider.enabled = true;
						
						if(follower.FinishTween)
						{
							ManagerGame.enableAction = true;
							currentBlockStage.doorEenterAnimation.Play("close");
							survivalState = SurvivalState.NORMAL;
							oldBlockStage.mySpawner.CleanEnemies();
							Destroy(oldBlockStage.gameObject);
						}
					}
				}
				
				break;
			}
		}
	}
	
	public void MoreOneElimined(int count)
	{
		enemiesElimined += count;
		if(!doorOpen && currentBlockStage.Elimined(count))
		{
			ManagerGame.enableAction = false;
			survivalState = SurvivalState.SHOW_DOOR;
			doorOpen = true;
		}
	}
}
